package com.github.xzb617.rpc.loadbalancer.strategy;

import com.github.xzb617.rpc.entity.Server;
import com.github.xzb617.rpc.loadbalancer.AbstractLoadBalancer;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 顺序轮询策略
 */
public class RoundRobinLoadBalancer extends AbstractLoadBalancer {

    private final AtomicInteger serverPositionCounter;

    public RoundRobinLoadBalancer() {
        this.serverPositionCounter = new AtomicInteger(0);
    }

    public Server chooseServer(List<Server> servers) {
        int position = this.acquireNextPosition(servers.size());
        return servers.get(position);
    }

    private synchronized int acquireNextPosition(int size) {
        int position = this.serverPositionCounter.getAndIncrement();
        if (position >= size) {
            this.serverPositionCounter.set(1);
            position = 0;
        }
        return position;
    }

}
